<template>
	<view>
		<xe-upload ref="XeUpload" :options="uploadOptions" @callback="handleUploadCallback"></xe-upload>

		<uni-popup type="bottom" ref="popup" :safe-area="false" @maskClick="close">

			<view class="box">
				<view style="padding: 10px">
					<view style="color: black;font-size: 32rpx;font-weight: bold">{{ message }}:{{ zipFileName }}</view>
					<view style="color: #666;font-size: 24rpx">&nbsp;&nbsp;提示:微信账单密码会发送至微信支付程序中,支付宝账单密码默认为身份证号码后六位。
					</view>
				</view>

				<view style="border-radius: 10px 10px 0 0;padding-bottom: 20px">
					<view class="item" style="padding: 10px">
						<password-input :numLng='password' :plaintext="false"></password-input>
					</view>
				</view>
				<monokeyboard :value="password" :show="true" :btnColor="systemTheme.bg" :minLength="6" :maxIntNum="6"
					:isDecimal="false" confirmText="确定" @change="get_number" @confirm="handleSave()">
				</monokeyboard>
			</view>

		</uni-popup>
	</view>
</template>

<script>
	import passwordInput from '@/components/password-input/password-input.vue'
	import monokeyboard from '@/components/keyboard/mono-keyboard.vue'
	import {
		useSystem
	} from "../../store/theme";

	import {
		getCustomTypeList,
		getRecordList,
		batchImport
	} from '@/api/api.js';
	import {
		saveFile,
		fetchFileData
	} from '@/common/file.js';

	export default {
		name: "settings",
		components: {
			passwordInput,
			monokeyboard
		},
		data() {
			return {
				type: null,
				uploadOptions: {
					// url: 'http://192.168.31.185:3000/api/upload', // 不传入上传地址则返回本地链接
				},
				importData: [],
				password: '',
				zipFileName: '',
				sourceUrl: '',
				message: '请输入zip密码',

				unZipDir: '/downloadFile'

			};
		},
		setup() {
			const systemTheme = useSystem()
			return {
				systemTheme
			}
		},
		async onLoad() {
			this.zipNext = null
		},
		emits: ['importSuccess'],
		methods: {
			async fetchFileData(codeType, fileName, callback) {
				plus.io.requestFileSystem(
					plus.io.PUBLIC_DOWNLOADS, // 文件系统中的根目录
					fs => {
						// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
						fs.root.getFile(fileName, {
							create: true // 文件不存在则创建
						}, fileEntry => {
							// 文件在手机中的路径
							fileEntry.file(function(file) {
								var fileReader = new plus.io.FileReader();
								fileReader.readAsText(file, codeType)
								fileReader.onloadend = function(res) { //读取文件内容成功后的回调事件
									callback(res.target.result)
								}
							});
						}, e => {
							console.log('报错111', "getFile failed: " + e.message);
						});
					},

					e => {
						console.log('报错222', e.message);
					}
				);
			},
			async weChatImport(data) {
				let importData = data;
				// importData = importData.replace(/\t/g, '');
				let headLineNum = 0
				const lines = importData.split('\n'); // 按行分割数据
				const headers = lines[headLineNum].split(','); // 获取表头数据
				const result = [];

				for (let i = headLineNum + 1; i < lines.length; i++) {
					const obj = {};
					const currentLine = lines[i].split(',');

					if (currentLine.length !== headers.length) {
						continue;
					}

					for (let j = 0; j < headers.length; j++) {
						obj[headers[j].slice(1, -1)] = currentLine[j].slice(1, -1);
					}
					result.push(obj);
				}
				// 遍历jsonData
				let dataArr = [];
				for (let i = 0; i < result.length; i++) {
					const jsonItem = result[i];
					const obj = {
						num: parseFloat(jsonItem["金额"].replace('¥', '')),
						type_id: jsonItem["类型"] === '收入' ? 34 : 26,
						title: jsonItem["分类"],
						title2: jsonItem["二级分类"],
						type: jsonItem["类型"] === '收入' ? 1 : 0,
						remark: jsonItem["分类"],
						image: '',
						create_time: jsonItem["时间"],
						icon: 'icon-weixinzhifu',
						import_id: jsonItem["ID"],
						old_type_key: jsonItem["类型"],
						account: jsonItem["账户1"],
						account: jsonItem["账户2"],
					}
					dataArr.push(obj)
				}
				console.log('dataArr', dataArr)
				// 存储临时数据
				if (dataArr != null && dataArr.length > 0) {
					dataArr.forEach((e) => {
						this.importData.push(e)
					})
				}
			},
			async handleUploadCallback(e) {
				if (e.data == null || e.data.length == 0) {
					return
				}
				this.importData = []
				// 解析文件list 入参 文件列表,数组下标
				await this.parseFileList(e.data, 0)
			},

			async parseFileList(fileList, index) {
				if (index >= fileList.length) {
					if (this.importData != null && this.importData.length > 0) {
						uni.setStorage({
							key: 'importData',
							data: this.importData,
							success: function() {
								console.log('success');
								uni.navigateTo({
									url: '/pages/import/index'
								})
							}
						});
					} else {
						uni.showModal({
							title: '提示',
							content: "导入完成，但未识别到数据，请选择正确文件",
							showCancel: false
						})
					}
				}


				const file = fileList[index];
				this.sourceUrl = file.tempFilePath
				// csv 文件
				if (file.type.includes("csv")) {
					if (this.type === 'weChat') {
						await this.fetchFileData("UTF-8", file.tempFilePath, async (data) => {
							console.log('csv 文件', data)
							await this.weChatImport(data);
							await this.parseFileList(fileList, index + 1)
						})
					}
					// zip解压
				} else if (file.type.includes("zip")) {
					await this.unZip(async (status = false) => {
						if (status) {
							await this.parseFileList(fileList, index)
							return
						}
						await this.parseFileList(fileList, index + 1)
					});
				} else {
					uni.showModal({
						title: '提示',
						content: "请选择正确文件(zip或已解压好的csv文件)",
						showCancel: false
					})
				}
			},
			async unZip(callback) {
				const zipUtil = uni.requireNativePlugin('ziputil');
				const obj = {
					sourceUrl: plus.io.convertLocalFileSystemURL(this.sourceUrl),
					targetDir: plus.io.convertLocalFileSystemURL('_doc' + this.unZipDir),
					codeType: "UTF-8",
					password: this.password

				}
				console.log(obj)
				zipUtil.unZip(obj, (res) => {
					console.log(res)
					this.parseZipResult(res, callback)
				})
			},
			parseZipResult(res, callback) {
				const _this = this;
				if (res.code === 2) {
					_this.zipFileName = res.sourceFileName
					_this.message = '请输入密码'
					_this.$refs.popup.open()
					_this.$refs.KeyboarHid.open();

					_this.zipNext = callback;

				} else if (res.code === 3) {
					console.log(callback)
					console.log(_this)
					_this.zipFileName = res.sourceFileName
					_this.message = '密码错误'
					_this.$refs.popup.open()

					_this.zipNext = callback;
				} else if (res.code === -1) {
					uni.showModal({
						title: '解压失败',
						content: res.message,
						showCancel: false,
						success: res => {
							callback(false)
						}
					})
				} else if (res.code === 1) {
					let fileArr = res.data;
					if (fileArr != null && fileArr.length > 0) {
						for (const file of fileArr) {
							console.log(file)
							if (_this.type === 'weChat') {
								this.fetchFileData("UTF-8", "_doc/" + file.fileUrl, async (data) => {
									await _this.weChatImport(data);
									callback(false)
								})
							} else if (_this.type === 'aliPay') {
								this.fetchFileData("GB2312", "_doc/" + file.fileUrl, async (data) => {
									await _this.aliPayImport(data);
									callback(false)
								})
							}
						}
					}
				}
			},
			get_number(val) {
				this.password = val;
			},
			async handleSave() {
				await this.$refs.popup.close()

				setTimeout(() => {
					this.zipNext(true);
				}, 500);
			},
			handleUploadClick(type) {
				console.log(type)
				this.type = type
				this.$refs.XeUpload.upload('file', {});
			},
			// 导出数据
			async exportFile() {
				const customTypeList = await getCustomTypeList();
				const recordList = (await getRecordList()).list;
				const obj = {
					customTypeList,
					recordList
				}
				saveFile('myAccounts.txt', obj, (res) => {
					if (res) {
						uni.showToast({
							title: "导出成功"
						})
					}
				})
			},
			// 导入数据
			async importFile() {
				const self = this
				fetchFileData('myAccounts.txt', async (res) => {
					await batchImport(res)
					await self.$emit('importSuccess')

				})
			},
			// 数据迁移
			dataMigration() {
				const self = this;
				uni.showActionSheet({
					itemList: ['导入', '导出'],
					success: async function(res) {
						// console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
						switch (res.tapIndex) {
							case 0:
								await self.handleUploadClick("weChat")
								break;
							case 1:
								// 导出
								await self.exportFile()
								break;
						}
					},
				});


			},
			// 显示设置操作按钮
			handleSet() {
				this.dataMigration()
			},
		}
	}
</script>

<style>
	.item {
		padding: 10rpx 0rpx;
	}

	.box {
		padding: 15px;
		background-color: #F7F7F7;
		border-radius: 10px 10px 0 0;
		display: flex;
		flex-direction: column;
	}
</style>